import { AgentMCPBridge, AgentConfig } from '../core/agent-mcp-bridge';

async function multiRoundToolExample() {
  console.log('=== Multi-Round Tool Calling Example ===');
  
  const agentConfig: AgentConfig = {
    name: 'MultiRoundAgent',
    description: 'Agent demonstrating multi-round tool calling',
    systemPrompt: 'You are a helpful assistant that can use multiple tools in sequence to complete complex tasks. When you get tool results, analyze them and determine if you need more tools to complete the task.',
    mcpClients: [
      {
        serverUrl: 'ws://localhost:8080/mcp',
        timeout: 30000,
        retryCount: 3
      }
    ]
  };

  const agent = new AgentMCPBridge(agentConfig);
  
  try {
    await agent.initialize();
    
    console.log('Agent initialized with multi-round tool calling capability');
    
    // 模拟需要多轮工具调用的复杂任务
    const complexTasks = [
      '帮我分析北京的天气，然后计算温度转换，最后给出建议',
      '比较北京和上海的天气差异，并计算两地温差',
      '获取多个城市的天气信息并进行统计分析'
    ];
    
    for (const task of complexTasks) {
      console.log(`\n📋 Task: ${task}`);
      console.log('Starting multi-round tool execution...\n');
      
      const response = await agent.processMessage({
        role: 'user',
        content: task
      });
      
      console.log(`\n🎯 Final Response:`);
      console.log(response.content);
      
      console.log('\n' + '='.repeat(50));
      
      await new Promise(resolve => setTimeout(resolve, 3000));
    }
    
  } catch (error) {
    console.error('Multi-round example failed:', error);
  } finally {
    await agent.shutdown();
  }
}

// 工作流程说明
function explainMultiRoundLogic() {
  console.log(`
🔄 Multi-Round Tool Calling Logic:

1. Initial Request
   ├─ User sends message
   ├─ LLM analyzes and calls first set of tools
   └─ Agent executes tools and gets results

2. Round 1 Results
   ├─ Agent sends tool results back to LLM
   ├─ LLM analyzes results and decides:
   │  ├─ If needs more info → calls additional tools
   │  └─ If has enough info → generates final response
   └─ If more tools needed → continue to Round 2

3. Round 2+ Results
   ├─ Agent executes new tools
   ├─ Sends all results (previous + new) to LLM
   ├─ LLM continues analysis
   └─ Process repeats until:

4. Termination Conditions
   ├─ LLM decides no more tools needed
   ├─ Tool call fails (error handling)
   ├─ Max rounds reached (5 rounds limit)
   └─ Network/LLM error

🛡️ Safety Features:
   • Max round limit (5 rounds) prevents infinite loops
   • Error handling stops execution on tool failures
   • Complete conversation history maintained
   • Progress logging for debugging

💡 Example Use Cases:
   • Weather analysis → temperature conversion → recommendations
   • Multi-city data collection → comparison → statistics
   • Data retrieval → calculation → formatting → presentation
`);
}

export { multiRoundToolExample, explainMultiRoundLogic };

if (require.main === module) {
  explainMultiRoundLogic();
  multiRoundToolExample().catch(console.error);
}